package com.desire.interceptor;

import com.desire.bean.TokenVerifyBean;
import com.desire.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author LittleDesire
 * @description
 * @date 2022-05-09 周一 14:49
 * @since 17
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtils tokenUtils;


    /**
     * 判断请求头中是否含有token信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 默认请求可以访问
        boolean result = true;

        String info = null;

        Object token = request.getHeader("x-token");

        if (null == token) {
            // 没有token则直接返回false

            info = error("您无权访问");
            // 无权访问
            result = false;
        } else {
            // 进行token验证
            TokenVerifyBean bean = tokenUtils.verifyToken(token.toString());
            if (bean.getCode() != 200) {
                info = error(bean.getMsg());
                result = false;
            }
        }

        if (!result) {
            // 无权访问 响应客户端请求
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(info);
            return false;
        }

        return true;
    }

    String error(String msg) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"code\":0,");
        sb.append("\"msg\":");
        sb.append("\"");
        sb.append(msg);
        sb.append("\"");
        sb.append("}");
        return sb.toString();
    }
}

